package de.wolvan.window;

import javax.swing.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URISyntaxException;
import java.util.Iterator;

import de.wolvan.main.main;
import de.wolvan.references.*;
import de.wolvan.tools.data;

public class AddFriend extends JFrame implements ActionListener{
	
	private JButton add;
	private JButton back;
	
	private JLabel USERNAME;
	
	public static JTextField username;
	
	public static AddFriend frame;
	
	public static void renderGUI() {
		frame = new AddFriend("Add Friend");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(390,180);
		frame.setLayout(null);
		frame.setVisible(true);
	}
	
	public AddFriend(String title) {
		super(title);
		
		add = new JButton("Add Friend");
		add.setBounds(10,70,170,40);
		add.addActionListener(this);
		add(add);
		
		back = new JButton("Cancel");
		back.setBounds(190,70,170,40);
		back.addActionListener(this);
		add(back);
		
		USERNAME = new JLabel("Username:");
		USERNAME.setBounds(10,10,360,20);
		add(USERNAME);
		
		username = new JTextField("");
		username.setBounds(10,40,350,20);
		username.addActionListener(this);
		add(username);
	}
	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == back) {
			frame.setVisible(false);
			ChatWindow.frame.setVisible(true);
		}
		if(e.getSource() == username) {
			add.doClick();
		}
		if(e.getSource() == add) {
			if(!username.getText().equals("")) {
				boolean alreadyExists = false;
				Iterator iterator = ChatWindow.map.keySet().iterator();
			    while (iterator.hasNext()) {
			      String key = (String) iterator.next();
			      if(key.equals(username.getText().toLowerCase())) {
			    	  if(ChatWindow.noFriend.get(key)) {
			    		  ChatWindow.noFriend.put(key, false);
			    	  } else {
			    		  alreadyExists = true;
			    	  }
			      }
			      
			    }
			    if(alreadyExists) {
					JOptionPane.showMessageDialog(null, "You cannot add a friend twice!", "Friend already exists", 0, null);
			    } else {
			    	System.out.println("Adding " + username.getText().toLowerCase() + " as a friend");
			    	data.setProperty(LoginWindow.username.getText() + "_ximBuddies",data.getProperty(LoginWindow.username.getText() + "_ximBuddies") + ";" + username.getText().toLowerCase());
			    	xim.buddies = data.getProperty(LoginWindow.username.getText() + "_ximBuddies");
			    	main.c.send("XIM_BUDDIES " + xim.buddies);
			    	ChatWindow.redrawUserList(ChatWindow.users.getSelectedIndex());
			    	username.setText("");
			    	frame.setVisible(false);
			    }
			} else {
				JOptionPane.showMessageDialog(null, "Please enter your friend's name!", "Empty Name", 0, null);
			}
		}
	}

}
